package com.kclm.xsap.web.controller;

import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;

/*********************
 * @Author: yejf
 * 生成验证码的控制器
 */
@Controller
@RequestMapping("/captcha")
@Slf4j
public class CaptchaController {

    @GetMapping("/default")
    public void generateCaptcha(HttpServletRequest request,
                                HttpServletResponse response) throws IOException {
        log.debug("==>生成验证码，指定响应头");
        // 指定响应头
        setHeader(response);
        // 生成验证码对象， 三个参数分别是宽、高、位数
        SpecCaptcha captcha = new SpecCaptcha(130, 48, 5);
        //设置验证码的字符类型为数字和字母混合
        captcha.setCharType(Captcha.TYPE_DEFAULT);
        // 设置内置字体
        captcha.setCharType(Captcha.FONT_1);
        log.debug("==>验证码的宽为{},高为{},位数是：{}", 130, 48, 5);
        String text = captcha.text().toLowerCase();
        log.debug("==> 本次验证码:{}", text);
        //验证码存入session
        request.getSession().setAttribute("verifyCode",text);
        //输出图片流
        captcha.out(response.getOutputStream());
    }

    @GetMapping("/arithmetic")
    public void generateArithmeticCaptcha(HttpServletRequest request,
                                          HttpServletResponse response)throws IOException {
        log.debug("==>生成数字计算类的验证码，指定响应头");
        // 指定响应头
        setHeader(response);
        // 生成验证码对象， 三个参数分别是宽、高、位数, ArithmeticCaptcha默认位数是2
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48, 3);
        log.debug("==>验证码的宽为{},高为{},位数是：{}", 130, 48, 3);
        String arithmeticString = captcha.getArithmeticString();
        log.debug("==> 本次数字计算验证码表达式：{}", arithmeticString);
        String text = captcha.text();
        log.debug("==> 本次数字计算验证码的结果是:{}", text);
        //验证码存入session
        request.getSession().setAttribute("verifyCode",text);
        //输出图片流
        captcha.out(response.getOutputStream());
    }

    private void setHeader(HttpServletResponse response) {
        response.setHeader("Cache-Control","no-store");
        response.setHeader("Pragma","no-cache");
        response.setDateHeader("Expires",0);
        response.setContentType("image/gif");
    }
}
